package com.dawnClass.service.impl;

import com.dawnClass.mapper.ConsumerCourseMapper;
import com.dawnClass.mapper.ConsumerOrderMapper;
import com.dawnClass.mapper.FlowMapper;
import com.dawnClass.pojo.*;
import com.dawnClass.service.PayService;
import com.dawnClass.util.ServiceResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class PayServiceImpl implements PayService {
    @Autowired
    private ConsumerOrderMapper orderMapper;
    @Autowired
    private FlowMapper flowMapper;
    @Autowired
    private ConsumerCourseMapper consumerCourseMapper;

    @Override
    public int updateOrderflow(String orderNum) {
        ConsumerOrderExample consumerOrderExample = new ConsumerOrderExample();
        consumerOrderExample.createCriteria().andOrderNumEqualTo(orderNum);
        List<ConsumerOrder> consumerOrders = orderMapper.selectByExample(consumerOrderExample);
        ConsumerOrder order = new ConsumerOrder();
        if (consumerOrders.size() > 0){
            order = consumerOrders.get(0);
            order.setOrdPayState(3);

            //修改订单
            orderMapper.updateByPrimaryKeySelective(order);

            Flow flow = new Flow();
            flow.setOrderId(order.getOrderId());
            flow.setCourseId(order.getCourseId());
            flow.setCollageState(0);
            flow.setFlowCost(order.getOrderTotal());
            flow.setFlowPayTime(new Date());
            flow.setFlowState(1);
            //添加流水
            flowMapper.insert(flow);

            //添加用户课程信息
            ConsumerCourse consumerCourse = new ConsumerCourse();
            consumerCourse.setCourseId(order.getCourseId());
            consumerCourse.setConsumerId(order.getConsumerId());
            consumerCourse.setLearningStartTime(new Date());
            consumerCourseMapper.insert(consumerCourse);
        }
        return order.getCourseId();
    }

    @Override
    public ServiceResponse getByOrdNum(String orderNum) {

        ConsumerOrderExample consumerOrderExample = new ConsumerOrderExample();
        consumerOrderExample.createCriteria().andOrderNumEqualTo(orderNum);
        ConsumerOrder consumerOrder = orderMapper.selectByExample(consumerOrderExample).get(0);


        FlowExample flowExample = new FlowExample();
        flowExample.createCriteria().andOrderIdNotEqualTo(consumerOrder.getOrderId());
        List<Flow> flows = flowMapper.selectByExample(flowExample);
        if (flows.isEmpty()){
            return ServiceResponse.getFail(null);
        }else {
            return ServiceResponse.getSuccess(flows.get(0));
        }
    }

}
